package first.group.ssh.packet;

import first.group.ssh.SSHConsts;
import first.group.ssh.packet.reader.IntegerReader;
import first.group.ssh.packet.reader.StringReader;
import first.group.ssh.packet.writer.StringWriter;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ChannelDataPacket extends Packet {

    public final int recipientChannel;
    public final byte[] data;

    public ChannelDataPacket(int recipientChannel, byte[] data) {
        super(SSHConsts.SSH_MSG_CHANNEL_DATA);
        this.recipientChannel = recipientChannel;
        this.data = data;
    }

    public static PacketParser<ChannelDataPacket> PARSER = new ChannelDataPacket.Parser();

    private static class Parser extends PacketParser<ChannelDataPacket> {

        @Override
        public ChannelDataPacket parse(ByteBuffer buffer) {
            var recipientChannel = IntegerReader.readInteger(buffer);
            if (recipientChannel == null) {
                return null;
            }
            var data = StringReader.readByteArray(buffer);
            if (data == null) {
                return null;
            }
            return new ChannelDataPacket(recipientChannel, data);
        }
    }

    @Override
    public void write(ByteBuffer buffer) {
        buffer.putInt(recipientChannel);
        StringWriter.writeByteArray(buffer, data);
    }

    @Override
    public String toString() {
        return "ChannelDataPacket{" + "recipientChannel=" + recipientChannel + ", data=" + new String(data, StandardCharsets.UTF_8) + "}";
    }
}
